package cr

import (
	"context"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/asserts"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/beans"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/loggers"
	"gitee.com/shiqiyue/xd-bi/internal/pkg/instance"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	gormopentracing "gorm.io/plugin/opentracing"
	"time"
)

func DbInit(ctx context.Context) {
	dbConfig := instance.GetConfig().Db
	// 主节点
	var masterDsn = dbConfig.Master.GetDsn()

	var err error
	newLogger := loggers.NewGormLogger(100*time.Millisecond, []string{"/srv/"})
	DB, err := gorm.Open(postgres.Open(masterDsn), &gorm.Config{QueryFields: true, Logger: newLogger})
	asserts.Nil(err, err)
	err = DB.Use(gormopentracing.New())
	asserts.Nil(err, err)

	instance.SetDb(DB)

	// 设置连接池
	sqlDB, err := DB.DB()
	asserts.Nil(err, err)

	// SetMaxIdleConns 设置空闲连接池中连接的最大数量
	sqlDB.SetMaxIdleConns(dbConfig.DbPool.MaxIdleConn)

	// SetMaxOpenConns 设置打开数据库连接的最大数量。
	sqlDB.SetMaxOpenConns(dbConfig.DbPool.MaxOpenConn)

	// SetConnMaxLifetime 设置了连接可复用的最大时间。
	sqlDB.SetConnMaxLifetime(dbConfig.DbPool.MaxLifeTime)

	/*	err = DB.AutoMigrate(&model.ReportResultColumn{})
		asserts.Nil(err, err)*/

	err = beans.ProvideBean(DB)
	asserts.Nil(err, err)
}
